<template>
    <el-drawer
        v-model="isShow"
        title="排班日期"
        :destroy-on-close="true"
        size="50%"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :show-close="false"
    >
        <div class="scheduleDate">
            <div class="date">当前排班日期：{{ queryForms.date }}</div>
        </div>
        <el-form
            ref="queryFormsRef"
            :model="queryForms"
            label-width="auto"
            label-position="right"
            :rules="queryRules"
        >
            <el-form-item label="值班负责人" required prop="dutyManager">
                <el-select
                    v-model="queryForms.dutyManager"
                    multiple
                    placeholder="请选择值班负责人"
                    @click="addScheduleManagerHandler"
                >
                    <el-option
                        v-for="item in policeResponsibleList"
                        :key="item.userId"
                        :label="item.userName"
                        :value="item.userId"
                    >
                    </el-option>
                </el-select>
                <!-- {{ policeResponsibleList }} -->
            </el-form-item>
            <el-form-item label="值班人员">
                <el-select
                    v-model="queryForms.otherDutyPersonnel"
                    multiple
                    placeholder="请选择值班人员"
                    @click="addScheduleDutyHandler"
                >
                    <el-option
                        v-for="item in otherDutyPersonnelList"
                        :key="item.userId"
                        :label="item.userName"
                        :value="item.userId"
                    >
                    </el-option>
                </el-select>
                <!-- {{otherDutyPersonnelList}}

                {{ queryForms.otherDutyPersonnel }} -->
            </el-form-item>
            <el-form-item label="值班时间" required>
                <el-col :span="11">
                    <el-form-item prop="startdate">
                        <el-time-picker
                            v-model="queryForms.startdate"
                            type="date"
                            placeholder="选择开始时间"
                            style="width: 100%"
                            value-format="HH:mm:ss"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="2" class="text-center">
                    <span class="text-gray-500">-</span>
                </el-col>
                <el-col :span="11">
                    <el-form-item prop="enddate">
                        <el-time-picker
                            v-model="queryForms.enddate"
                            placeholder="选择截止时间"
                            style="width: 100%"
                            value-format="HH:mm:ss"
                        />
                    </el-form-item>
                </el-col>
            </el-form-item>
            <el-form-item label="备注：">
                <el-input v-model="queryForms.remark" type="textarea" :rows="5"/>
            </el-form-item>

        </el-form>
        <template #footer>
            <el-button type="primary" @click="updateHandle(queryFormsRef)" v-if="isEdit">提交</el-button>
            <el-button type="primary" @click="submitHandle(queryFormsRef)" v-else>提交</el-button>
            <el-button type="danger" @click="deleteHandle" v-if="isEdit">删除</el-button>
            <el-button @click="changeShowStatus">关闭</el-button>
        </template>
    </el-drawer>

    <DutyManager
        ref="dutyManagerRef"
        @user="formatPoliceResponsible"
        :isClearData="isClearData"
    />
    <OtherDutyPersonnel
        ref="otherDutyPersonnelRef"
        @user="formatOtherDutyPersonnel"
        :isClearData="isClearData"
    />
</template>

<script setup>
import {useTemplateRef} from "vue";
import OtherDutyPersonnel from "@/views/PoliceWork/SetSchedu/components/OtherDutyPersonnel.vue";
import DutyManager from "@/views/PoliceWork/SetSchedu/components/DutyManager.vue";
import {
    addPoliceScheduleApi,
    deletePoliceScheduleApi,
    getPoliceScheduleDetailApi,
    updatePoliceScheduleApi
} from "@/api/SetSchedule/SetSchedule.js";
import dayjs from "dayjs";
import {useBailiffsStore} from "@/store/bailiffsStore.js";

const emit = defineEmits(['refresh-data']);
const bailiffsStore = useBailiffsStore();

const isShow = ref(false)
// 是否是编辑模式
const isEdit = ref(false)
// 默认提交参数
const defaultQueryForms = {
    // 日期
    date: '',
    // 警务区 ID
    policeareaId: '',
    // 值班负责人
    dutyManager: [],
    // 其他值班人
    otherDutyPersonnel: [],
    // 开始时间
    startdate: '',
    // 截止时间
    enddate: '',
    // 备注
    remark: ''
}
const queryForms = ref({...defaultQueryForms})
// 是否需要清空数据
const isClearData = ref(false);
// 值班负责人
const policeResponsibleList = ref({})
// 其他值班人员
const otherDutyPersonnelList = ref({})
// 执勤排班任务 ID
const scheduleId = ref('');
// 执勤详情内容
const scheduleDetail = ref({});

// 值班负责人点击次数
const dutyManagerCount = ref(0);
// 值班人员点击次数
const otherDutyPersonnelCount = ref(0);

// 变更显示状态
const changeShowStatus = () => {
    isShow.value = !isShow.value
    if (!isShow.value) {
        isClearData.value = false
        isEdit.value = false
        queryForms.value = {...defaultQueryForms}
        dutyManagerCount.value = 0
        otherDutyPersonnelCount.value = 0
    }
}

// 展开新增的执勤排班
const showAddSchedule = ({date, policeAreaId}) => {
    changeShowStatus()
    queryForms.value.date = date;
    queryForms.value.policeareaId = policeAreaId;
}

// 展开需要修改的执勤排班
const showEditSchedule = async (id) => {
    changeShowStatus()
    isEdit.value = true;
    scheduleId.value = id;
    await getDetail()
}
defineExpose({showAddSchedule, showEditSchedule})

const dutyManagerRef = useTemplateRef('dutyManagerRef')
const otherDutyPersonnelRef = useTemplateRef('otherDutyPersonnelRef')
const queryFormsRef = useTemplateRef('queryFormsRef')
const queryRules = reactive({
    dutyManager: [
        {required: true, message: '请选择值班负责人', trigger: 'blur'}
    ],
    otherDutyPersonnel: [
        {required: true, message: '请选择值班人员', trigger: 'blur'}
    ],
    startdate: [
        {required: true, message: '请选择执勤排班时间', trigger: 'blur'},
    ],
    enddate: [
        {required: true, message: '请选择执勤排班时间', trigger: 'blur'},
    ]
})

// 值班负责人优化处理
const formatPoliceResponsible = (row) => {

    policeResponsibleList.value = row;
    queryForms.value.dutyManager = row.map(item => item.userId);
}

// 其他值班人员优化处理
const formatOtherDutyPersonnel = (row) => {
    otherDutyPersonnelList.value = row;
    // Object.keys(row).map(item => {
    //     return row[item]['userId']
    // })
    // queryForms.value.otherDutyPersonnel = row.map(item => item.userId);
    queryForms.value.otherDutyPersonnel = Object.keys(row).map(item => {
        return row[item]['userId']
    })
}

// 获取详情
const getDetail = async () => {
    const res = await getPoliceScheduleDetailApi(scheduleId.value)
    scheduleDetail.value = res.data;
    const data = res.data;
    const jwPoliceList = data.jwSendpoliceList.filter(item => item.userId !== data.dutuserId);

    queryForms.value = {
        // 日期
        date: dayjs(data.startdate).format('YYYY-MM-DD'),
        // 警务区 ID
        policeareaId: data.policeareaId,
        // 值班负责人
        dutyManager: [data.dutuserId],
        // 其他值班人
        otherDutyPersonnel: jwPoliceList.map(item => item.userId),
        // 开始时间
        startdate: dayjs(data.startdate).format('HH:mm:ss'),
        // 截止时间
        enddate: dayjs(data.enddate).format('HH:mm:ss'),
        // 备注
        remark: data.remark
    };
    policeResponsibleList.value = [
        {
            userId: data.dutuserId,
            userName: data.dutUserName
        }
    ];

    otherDutyPersonnelList.value = jwPoliceList.map(item => {
        return {
            userId: item.userId,
            userName: item.userName
        }
    });

    bailiffsStore.setBailiffsId([Number(data.dutuserId)])

}

// 提交
const submitHandle = async (elForm) => {
    if (!elForm) return
    await elForm.validate(async (valid, fields) => {
            if (valid) {
                await addPoliceScheduleApi(getFormatQueryParams())
                    .then(() => {
                        changeShowStatus()
                        isClearData.value = true
                        emit('refresh-data', '')
                    })

            } else {
                console.log('error submit!', fields)
            }
        }
    )
}

// 更新
const updateHandle = async (elForm) => {
    if (!elForm) return
    await elForm.validate(async (valid, fields) => {
        if (valid) {
            await updatePoliceScheduleApi({
                ...getFormatQueryParams(),
                ...{
                    jwScheduleId: scheduleDetail.value.jwScheduleId
                }
            }).then(() => {
                changeShowStatus()
                isClearData.value = true
                emit('refresh-data', '')
            })

        } else {
            console.log('error update submit!', fields)
        }
    })
}

// 获取 创建与更新 的提交参数
const getFormatQueryParams = () => {
    return {
        policeareaId: queryForms.value.policeareaId,
        adduserId: 0,
        dutuserId: queryForms.value.dutyManager[0],
        startdate: `${queryForms.value.date} ${queryForms.value.startdate}`,
        enddate: `${queryForms.value.date} ${queryForms.value.enddate}`,
        state: '0',
        remark: queryForms.value.remark,
        jwSendpoliceList: [
            {
                sendDate: `${queryForms.value.date} ${queryForms.value.startdate}`,
                type: '1',
                userId: queryForms.value.dutyManager[0],
                state: '1'
            },
            ...queryForms.value.otherDutyPersonnel.map(item => {
                return {
                    sendDate: `${queryForms.value.date} ${queryForms.value.startdate}`,
                    type: '1',
                    userId: item.toString(),
                    state: '1'
                }
            })
        ]
    };
}

// 删除执勤排班
const deleteHandle = async () => {
    await deletePoliceScheduleApi(scheduleDetail.value.jwScheduleId)
        .then(() => {
            changeShowStatus()
            isClearData.value = true
            emit('refresh-data', '')
        })
}

// 添加值班负责人排班事件
const addScheduleManagerHandler = () => {
    dutyManagerCount.value += 1
    if (dutyManagerCount.value === 1 && !isEdit.value) {
        isClearData.value = true;
        policeResponsibleList.value = {}
    } else {
        isClearData.value = false;
    }
    dutyManagerRef.value.showSelect('值班负责人', policeResponsibleList);
}

// 添加值班人员排班事件
const addScheduleDutyHandler = () => {
    otherDutyPersonnelCount.value += 1
    if (otherDutyPersonnelCount.value === 1 && !isEdit.value) {
        isClearData.value = true;
        otherDutyPersonnelList.value = {}
    } else {
        isClearData.value = false;
    }
    otherDutyPersonnelRef.value.showSelect('值班人员', otherDutyPersonnelList);
}

</script>

<style scoped lang="scss">
.scheduleDate {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-bottom: 20px;

    .date {
        font-size: 14px;
        line-height: 22px;
    }
}

:deep(.el-tag__close) {
    display: none;
}

:deep().el-select__selected-item {
    margin-right: 10px;
}

:deep().el-tag {
    max-width: 300px !important;
}
</style>